<template>
  <div class="lost-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true">
        <el-form-item label="物品名称">
          <el-input v-model="searchParams.itemName" placeholder="输入名称" clearable />
        </el-form-item>
        <el-form-item label="丢失地点">
          <el-input v-model="searchParams.lostLocation" placeholder="输入地点" clearable />
        </el-form-item>
        <el-form-item label="丢失时间">
          <el-date-picker
            v-model="searchParams.lostTime"
            type="datetime"
            placeholder="选择时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="丢失者">
          <el-input v-model="searchParams.username" placeholder="输入用户名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadData">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="action-buttons">
        <el-button type="success" @click="openDialog('add')">新增失物</el-button>
        
        <!-- 导出Excel按钮 -->
        <el-button type="primary" @click="exportToExcel">
          <el-icon><Download /></el-icon>
          导出Excel
        </el-button>
        
        <!-- 导入Excel按钮 - 修改了 http-request -->
        <el-upload
          action=""
          :show-file-list="false"
          :before-upload="beforeExcelUpload"
          :http-request="importFromExcel"
          accept=".xlsx, .xls"
          style="display: inline-block; margin-left: 10px;"
        >
          <el-button type="warning">
            <el-icon><Upload /></el-icon>
            导入Excel
          </el-button>
        </el-upload>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" border stripe style="width: 100%"
    @sort-change="handleSortChange" 
    remote-sort>
      <el-table-column prop="id" label="ID" width="80"
      sortable
        :sort-orders="['ascending', 'descending']" />
      <el-table-column prop="itemName" label="物品名称" width="150" />
      <el-table-column prop="itemCategory" label="类别" width="100" />
     <el-table-column label="图片" width="120">
  <template #default="{ row }">
    <el-image
      style="width: 80px; height: 80px"
      :src="getImageUrl(row.image)"
      :preview-src-list="[getImageUrl(row.image)]"
      fit="cover"
    />
  </template>
</el-table-column>
      <el-table-column prop="lostLocation" label="丢失地点" width="150" />
      <el-table-column prop="lostTime" label="丢失时间" width="180" />
      <el-table-column prop="detailedDescription" label="详细描述" show-overflow-tooltip />
      <el-table-column prop="username" label="发布人" width="120" />
      <el-table-column prop="createdAt" label="创建时间" width="180">
      <template #default="{ row }">
        {{ formatDate(row.createdAt) }}
      </template>
    </el-table-column>
    <el-table-column prop="locate" label="送达地点" width="180"></el-table-column>
    <el-table-column prop="fullName" label="姓名" width="120" />
    <el-table-column prop="phone" label="手机号" width="150" />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="openDialog('edit', row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="pagination.current"
      v-model:page-size="pagination.size"
      :total="pagination.total"
      :page-sizes="[5, 10, 20]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="loadData"
      @current-change="loadData"
    />

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted,onActivated } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router=useRouter()
const token = localStorage.getItem('token');
const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN');
};
interface LostItemDTO {
  id?: number
  itemName: string
  itemCategory: string
  lostLocation: string
  lostTime: string
  detailedDescription: string
  image: string | null  // 允许为null
  locate:string
}

// 表格数据
const tableData = ref<LostItemDTO[]>([])
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 搜索参数
const searchParams = reactive({
  itemName: '',
  lostLocation: '',
  lostTime: '',
  username:''
})
const exportToExcel = async () => {
  try {
    const token = localStorage.getItem('token');
    // 构建与当前搜索条件相同的参数
    const params = {
      itemName: searchParams.itemName,
      lostLocation: searchParams.lostLocation,
      lostTime: searchParams.lostTime,
      username: searchParams.username
    };

    // 使用当前搜索条件导出
    const response = await axios.get('/lost/export', {
      params,
      responseType: 'blob',
      headers: { Authorization: `Bearer ${token}` }
    });
    
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '失物数据.xlsx');
    document.body.appendChild(link);
    link.click();
    
    // 清理
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    
    ElMessage.success('导出成功');
  } catch (error) {
    ElMessage.error('导出失败: ' + (error as Error).message);
  }
};
// 导入Excel前的验证
const beforeExcelUpload = (file: File) => {
  const isExcel = /\.(xlsx|xls)$/.test(file.name.toLowerCase());
  if (!isExcel) {
    ElMessage.error('只能上传Excel文件!');
    return false;
  }
  return true;
};

// 导入Excel
const importFromExcel = async (options: any) => {
  try {
    const token = localStorage.getItem('token');
    const formData = new FormData();
    formData.append('file', options.file);
    
    // 使用正确的导入路径
    const response = await axios.post('/lost/import', formData, {
      headers: { 
        'Content-Type': 'multipart/form-data',
        Authorization: `Bearer ${token}` 
      }
    });
    
    // 处理响应数据
    if (response.data.status === 'success') {
      ElMessage.success(response.data.message);
      loadData(); // 重新加载数据
    } else {
      ElMessage.error(response.data.message || '导入失败');
    }
  } catch (error: any) {
    let errorMessage = '导入失败';
    if (error.response && error.response.data && error.response.data.message) {
      errorMessage += ': ' + error.response.data.message;
    } else if (error.message) {
      errorMessage += ': ' + error.message;
    }
    ElMessage.error(errorMessage);
  }
};

// 加载数据
const loadData = async () => {
  try {
    const params = {
      page: pagination.current,
      pageSize: pagination.size,
      itemName: searchParams.itemName,
      lostLocation: searchParams.lostLocation,
      lostTime: searchParams.lostTime,
      username: searchParams.username,
      sortField: sortParams.sortField,
      sortOrder: sortParams.sortOrder
    }
    const { data } = await axios.get('/lost/page', { 
      params,
      headers: { Authorization: `Bearer ${token}` }  // 添加认证头
    })
    tableData.value = data.data
    pagination.total = data.total
  } catch (error) {
    ElMessage.error('数据加载失败')
  }
}
// 排序参数
const sortParams = reactive({
  sortField: 'id', // 默认排序字段
  sortOrder: 'desc' // 默认排序方向
})

// 处理排序变化
const handleSortChange = ({ prop, order }: { prop: string; order: 'ascending' | 'descending' | null }) => {
  if (prop === 'id') {
    sortParams.sortField = prop
    sortParams.sortOrder = order === 'ascending' ? 'asc' : 'desc'
    loadData()
  }
}
// 重置搜索
const resetSearch = () => {
  Object.assign(searchParams, {
    itemName: '',
    lostLocation: '',
    lostTime: '',
    username:''
  })
  loadData()
}

const openDialog = (type: 'add' | 'edit', row?: LostItemDTO) => {
  if (type === 'edit' && row) {
    router.push({
      name: 'ItemEdit',
      params: { id: row.id },
      query: { type: 'lost' }
    })
  } else {
    router.push({
      name: 'ItemEdit',
      query: { type: 'lost' }
    })
  }
}
onActivated(() => {
  loadData()
})
// 删除操作
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确认删除该记录吗？', '警告', { type: 'warning' })
    await axios.delete(`/lost/delete/${id}`,{
       headers: {
        Authorization: `Bearer ${token}`  // 在请求头中添加 Token
      }
    })
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    // 取消删除不处理
  }
}

const getImageUrl = (path: string | null) => {
  if (!path || path === 'null') {
    return ''; // 返回默认图片或空字符串
  }
  // 处理路径中的反斜杠（Windows系统可能使用反斜杠）
  const normalizedPath = path.replace(/\\/g, '/');
  // 确保路径以/uploads/开头
  if (!normalizedPath.startsWith('/uploads/') && !normalizedPath.startsWith('uploads/')) {
    return `http://localhost:8080/uploads/${normalizedPath}`;
  }
  
  // 直接使用后端返回的路径
  return `http://localhost:8080${normalizedPath.startsWith('/') ? '' : '/'}${normalizedPath}`;
}

// 初始化加载
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.lost-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.preview-image {
  margin-top: 10px;
  max-width: 200px;
  max-height: 200px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>